{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Merge Overlapping Intervals\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/IjHjUgHaaeRr2UIB98P91A)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given an array of intervals - that is, an array of tuples `(start, end)`. The array may not be sorted, and could contain overlapping intervals. Return another array where the overlapping intervals are merged."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```python3\n",
    "[(1, 3), (5, 8), (4, 10), (20, 25)]\n",
    "```\n",
    "\n",
    "This input should return `[(1, 3), (4, 10), (20, 25)]` since `(5, 8)` and `(4, 10)` can be merged into `(4, 10)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def merge(intervals):\n",
    "    # Convert intervals into an array of sets.\n",
    "    arrays = [{j for j in range(i[0], i[-1] + 1)} for i in intervals]\n",
    "\n",
    "    i = 0\n",
    "    j = 1\n",
    "\n",
    "    # Traverse all sets in the array.\n",
    "    while i < len(arrays) - 1:\n",
    "        while j < len(arrays):\n",
    "\n",
    "            # Check the coverage of 2 sets.\n",
    "            if arrays[i].issubset(arrays[j]):\n",
    "                arrays.remove(arrays[i])\n",
    "                pass\n",
    "            elif arrays[i].issuperset(arrays[j]):\n",
    "                arrays.remove(arrays[j])\n",
    "                pass\n",
    "\n",
    "            else:\n",
    "                j += 1\n",
    "            pass\n",
    "            i += 1\n",
    "            j = i + 1\n",
    "        pass\n",
    "    return [(min(k), max(k)) for k in arrays]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(1, 3), (4, 10), (20, 25)]\n"
     ]
    }
   ],
   "source": [
    "print(merge([(1, 3), (5, 8), (4, 10), (20, 25)]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
